from flask import Blueprint, request, jsonify
from models import Ward, Bed, Device
import logging

logger = logging.getLogger(__name__)

wards_bp = Blueprint('wards', __name__, url_prefix='/api/wards')


@wards_bp.route('', methods=['GET'])
def get_wards():
    """获取病房列表"""
    try:
        # 获取查询参数
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('pageSize', 20))
        search = request.args.get('search', '')
        
        # 构建查询条件
        filters = {}
        if search:
            filters['$or'] = [
                {'wardName': {'$regex': search, '$options': 'i'}},
                {'wardNumber': {'$regex': search, '$options': 'i'}}
            ]
        
        # 计算分页
        skip = (page - 1) * page_size
        
        # 查询数据
        wards = Ward.find_all(filters, skip=skip, limit=page_size)
        total = Ward.count(filters)
        
        # 为每个病房添加床位统计信息
        for ward in wards:
            beds = Bed.find_by_ward(ward['_id'])
            ward['bedCount'] = len(beds)
            ward['occupiedCount'] = sum(1 for bed in beds if bed.get('deviceId'))
        
        return jsonify({
            'code': 200,
            'message': '成功',
            'data': {
                'list': wards,
                'total': total,
                'page': page,
                'pageSize': page_size
            }
        })
    except Exception as e:
        logger.error(f"获取病房列表失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@wards_bp.route('/<ward_id>', methods=['GET'])
def get_ward(ward_id):
    """获取病房详情"""
    try:
        ward = Ward.find_by_id(ward_id)
        
        if not ward:
            return jsonify({
                'code': 404,
                'message': '病房不存在'
            }), 404
        
        # 获取病房的床位列表
        beds = Bed.find_by_ward(ward_id)
        
        # 为每个床位添加设备信息
        for bed in beds:
            if bed.get('deviceId'):
                device = Device.find_by_id(bed['deviceId'])
                bed['device'] = device
        
        ward['beds'] = beds
        
        return jsonify({
            'code': 200,
            'message': '成功',
            'data': ward
        })
    except Exception as e:
        logger.error(f"获取病房详情失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@wards_bp.route('', methods=['POST'])
def create_ward():
    """创建病房"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('wardName'):
            return jsonify({
                'code': 400,
                'message': '病房名称不能为空'
            }), 400
        
        # 创建病房
        ward = Ward.create(data)
        
        return jsonify({
            'code': 200,
            'message': '病房创建成功',
            'data': ward
        })
    except Exception as e:
        logger.error(f"创建病房失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@wards_bp.route('/<ward_id>', methods=['PUT'])
def update_ward(ward_id):
    """更新病房信息"""
    try:
        data = request.get_json()
        
        # 检查病房是否存在
        ward = Ward.find_by_id(ward_id)
        if not ward:
            return jsonify({
                'code': 404,
                'message': '病房不存在'
            }), 404
        
        # 更新病房
        success = Ward.update(ward_id, data)
        
        if success:
            return jsonify({
                'code': 200,
                'message': '病房更新成功'
            })
        else:
            return jsonify({
                'code': 400,
                'message': '病房更新失败'
            }), 400
    except Exception as e:
        logger.error(f"更新病房失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@wards_bp.route('/<ward_id>', methods=['DELETE'])
def delete_ward(ward_id):
    """删除病房"""
    try:
        # 检查病房是否存在
        ward = Ward.find_by_id(ward_id)
        if not ward:
            return jsonify({
                'code': 404,
                'message': '病房不存在'
            }), 404
        
        # 检查病房下是否有床位
        beds = Bed.find_by_ward(ward_id)
        if beds:
            return jsonify({
                'code': 400,
                'message': '病房下存在床位，无法删除。请先删除所有床位。'
            }), 400
        
        # 删除病房
        success = Ward.delete(ward_id)
        
        if success:
            return jsonify({
                'code': 200,
                'message': '病房删除成功'
            })
        else:
            return jsonify({
                'code': 400,
                'message': '病房删除失败'
            }), 400
    except Exception as e:
        logger.error(f"删除病房失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@wards_bp.route('/<ward_id>/beds', methods=['GET'])
def get_ward_beds(ward_id):
    """获取病房的床位列表"""
    try:
        # 检查病房是否存在
        ward = Ward.find_by_id(ward_id)
        if not ward:
            return jsonify({
                'code': 404,
                'message': '病房不存在'
            }), 404
        
        # 获取床位列表
        beds = Bed.find_by_ward(ward_id)
        
        # 为每个床位添加设备信息
        for bed in beds:
            if bed.get('deviceId'):
                device = Device.find_by_id(bed['deviceId'])
                bed['device'] = device
        
        return jsonify({
            'code': 200,
            'message': '成功',
            'data': beds
        })
    except Exception as e:
        logger.error(f"获取床位列表失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@wards_bp.route('/<ward_id>/beds', methods=['POST'])
def create_bed(ward_id):
    """创建床位"""
    try:
        # 检查病房是否存在
        ward = Ward.find_by_id(ward_id)
        if not ward:
            return jsonify({
                'code': 404,
                'message': '病房不存在'
            }), 404
        
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('bedNumber'):
            return jsonify({
                'code': 400,
                'message': '床位号不能为空'
            }), 400
        
        # 设置病房ID
        data['wardId'] = ward_id
        
        # 创建床位
        bed = Bed.create(data)
        
        return jsonify({
            'code': 200,
            'message': '床位创建成功',
            'data': bed
        })
    except Exception as e:
        logger.error(f"创建床位失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@wards_bp.route('/<ward_id>/beds/<bed_id>', methods=['PUT'])
def update_bed(ward_id, bed_id):
    """更新床位信息"""
    try:
        data = request.get_json()
        
        # 检查床位是否存在
        bed = Bed.find_by_id(bed_id)
        if not bed:
            return jsonify({
                'code': 404,
                'message': '床位不存在'
            }), 404
        
        # 检查床位是否属于该病房
        if bed['wardId'] != ward_id:
            return jsonify({
                'code': 400,
                'message': '床位不属于该病房'
            }), 400
        
        # 不允许修改wardId
        if 'wardId' in data:
            del data['wardId']
        
        # 更新床位
        success = Bed.update(bed_id, data)
        
        if success:
            return jsonify({
                'code': 200,
                'message': '床位更新成功'
            })
        else:
            return jsonify({
                'code': 400,
                'message': '床位更新失败'
            }), 400
    except Exception as e:
        logger.error(f"更新床位失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@wards_bp.route('/<ward_id>/beds/<bed_id>', methods=['DELETE'])
def delete_bed(ward_id, bed_id):
    """删除床位"""
    try:
        # 检查床位是否存在
        bed = Bed.find_by_id(bed_id)
        if not bed:
            return jsonify({
                'code': 404,
                'message': '床位不存在'
            }), 404
        
        # 检查床位是否属于该病房
        if bed['wardId'] != ward_id:
            return jsonify({
                'code': 400,
                'message': '床位不属于该病房'
            }), 400
        
        # 检查床位是否已绑定设备
        if bed.get('deviceId'):
            return jsonify({
                'code': 400,
                'message': '床位已绑定设备，请先解绑设备'
            }), 400
        
        # 删除床位
        success = Bed.delete(bed_id)
        
        if success:
            return jsonify({
                'code': 200,
                'message': '床位删除成功'
            })
        else:
            return jsonify({
                'code': 400,
                'message': '床位删除失败'
            }), 400
    except Exception as e:
        logger.error(f"删除床位失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@wards_bp.route('/<ward_id>/beds/<bed_id>/bind', methods=['POST'])
def bind_device_to_bed(ward_id, bed_id):
    """绑定设备到床位"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('deviceId'):
            return jsonify({
                'code': 400,
                'message': '设备ID不能为空'
            }), 400
        
        device_id = data['deviceId']
        
        # 检查床位是否存在
        bed = Bed.find_by_id(bed_id)
        if not bed:
            return jsonify({
                'code': 404,
                'message': '床位不存在'
            }), 404
        
        # 检查床位是否属于该病房
        if bed['wardId'] != ward_id:
            return jsonify({
                'code': 400,
                'message': '床位不属于该病房'
            }), 400
        
        # 检查床位是否已绑定设备
        if bed.get('deviceId'):
            return jsonify({
                'code': 400,
                'message': '床位已绑定设备，请先解绑'
            }), 400
        
        # 检查设备是否存在
        device = Device.find_by_id(device_id)
        if not device:
            return jsonify({
                'code': 404,
                'message': '设备不存在'
            }), 404
        
        # 检查设备是否已绑定到其他床位
        existing_bed = Bed.find_by_device(device_id)
        if existing_bed:
            return jsonify({
                'code': 400,
                'message': f'设备已绑定到其他床位（床位号：{existing_bed.get("bedNumber")}）'
            }), 400
        
        # 绑定设备
        success = Bed.bind_device(bed_id, device_id)
        
        if success:
            return jsonify({
                'code': 200,
                'message': '设备绑定成功'
            })
        else:
            return jsonify({
                'code': 400,
                'message': '设备绑定失败'
            }), 400
    except Exception as e:
        logger.error(f"绑定设备失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500


@wards_bp.route('/<ward_id>/beds/<bed_id>/unbind', methods=['POST'])
def unbind_device_from_bed(ward_id, bed_id):
    """解绑床位的设备"""
    try:
        # 检查床位是否存在
        bed = Bed.find_by_id(bed_id)
        if not bed:
            return jsonify({
                'code': 404,
                'message': '床位不存在'
            }), 404
        
        # 检查床位是否属于该病房
        if bed['wardId'] != ward_id:
            return jsonify({
                'code': 400,
                'message': '床位不属于该病房'
            }), 400
        
        # 检查床位是否已绑定设备
        if not bed.get('deviceId'):
            return jsonify({
                'code': 400,
                'message': '床位未绑定设备'
            }), 400
        
        # 解绑设备
        success = Bed.unbind_device(bed_id)
        
        if success:
            return jsonify({
                'code': 200,
                'message': '设备解绑成功'
            })
        else:
            return jsonify({
                'code': 400,
                'message': '设备解绑失败'
            }), 400
    except Exception as e:
        logger.error(f"解绑设备失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'服务器错误: {str(e)}'
        }), 500

